//
//  ViewController.m
//  二维码
//
//  Created by 王汉昌 on 15/11/30.
//  Copyright © 2015年 離去之原. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) UIView   *viewPreview;
@property (nonatomic, strong) UIView   *boxView;
@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic)         BOOL     isReading;//是否读取QRCode
@property (nonatomic, strong) CALayer  *scanLayer;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@end
@implementation ViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    _isReading = NO;
    _startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _startButton.frame = CGRectMake(150, 450, 80, 40);
    [_startButton addTarget:self action:@selector(startStopReading) forControlEvents:UIControlEventTouchUpInside];
    [_startButton setTitle:@"Start!" forState:UIControlStateNormal];
    _startButton.backgroundColor = [UIColor cyanColor];
    [_startButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.viewPreview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 400)];
    [self.view addSubview:self.viewPreview];
    [self.view addSubview:_startButton];
}

- (BOOL)startReading {
    NSError *error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@",[error localizedDescription]);
        return NO;
    }
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    _captureSession = [AVCaptureSession new];
    [_captureSession addInput:input];
    [_captureSession addOutput:captureMetadataOutput];
    //创建队列
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    //输出类型
    captureMetadataOutput.metadataObjectTypes = [NSArray arrayWithObject:AVMetadataObjectTypeQRCode];
    //显示layer
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    _videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    //将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    //设置扫描范围  rect是0~1之间
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    //扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height * 0.2f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.4f)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    [_viewPreview addSubview:_boxView];
    //扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    [_boxView.layer addSublayer:_scanLayer];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];
    //开始扫描
    [_captureSession startRunning];
    return YES;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            _isReading = NO;
        }
    }
}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        frame.origin.y += 5;
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (void)startStopReading{
    NSLog(@"2222");
    if (!_isReading) {
        if ([self startReading]) {
            [_startButton setTitle:@"Stop" forState:UIControlStateNormal];
            
        }
    }
    else{
        [self stopReading];
        [_startButton setTitle:@"Start!" forState:UIControlStateNormal];
    }
    _isReading = !_isReading;
}
-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (UIButton *)startButton {
//    if (nil == _startButton) {
//        _startButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        _startButton.frame = CGRectMake(150, 450, 80, 40);
//        [_startButton addTarget:self action:@selector(startStopReading) forControlEvents:UIControlEventTouchUpInside];
//        [_startButton setTitle:@"Start!" forState:UIControlStateNormal];
//        _startButton.backgroundColor = [UIColor cyanColor];
//        [_startButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    }
//    return _startButton;
//}
@end
